package com.zx.cloud.service;

import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zx.cloud.Shift;
import com.zx.cloud.controller.StatusCode;
import com.zx.cloud.domain.Role;
import com.zx.cloud.domain.RoleResource;
import com.zx.cloud.domain.UserRole;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.RoleMapper;
import com.zx.cloud.persistence.RoleResourceMapper;
import com.zx.cloud.persistence.UserRoleMapper;
import com.zx.cloud.util.Page;

/**
 * 角色
 */
@Service
@Transactional
public class RoleService extends CrudServiceImpl<Role> {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RoleService.class);

	@Autowired
	private RoleResourceService roleResourceService;

	@Autowired
	private RoleResourceMapper roleResourceMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	public RoleService(CrudMapper<Role> mapper) {
		super(mapper);
	}

	/**
	 * 
	 * @param 添加角色
	 * @param gmc
	 * @param role
	 *            角色实体类
	 * @return
	 */
	public int insertRole(Role role) {
		if (StringUtils.isEmpty(role.getName())) {
			LOGGER.error("添加角色姓名为空");
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS);
		}
		// 设置添加当前时间
		role.setCreateDate(OffsetDateTime.now());
		if (super.insert(role) > 0 && role.getResourceIds().size() > 0) {
			// 循环添加权限
			for (int i = 0; i < role.getResourceIds().size(); i++) {
				RoleResource roleResource = new RoleResource();
				roleResource.setRoleId(role.getId());
				roleResource.setResourceId(role.getResourceIds().get(i));
				roleResourceService.insert(roleResource);
			}
		}
		return 1;
	}

	/**
	 * 
	 * @param 修改角色
	 * @param gmc
	 * @param role
	 *            角色实体类
	 * @return
	 */
	public int updateRole(Role role) {
		if (StringUtils.isEmpty(role.getName())) {
			LOGGER.error("修改角色姓名为空");
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS);
		}
		// 设置修改当前时间
		role.setUpdateDate(OffsetDateTime.now());
		int boo = super.update(role);

		// 需补全权限操作
		if (boo > 0) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(role.getId());
			roleResourceService.deleteByRoleId(roleResource);
			if (role.getResourceIds().size() > 0) {
				for (int i = 0; i < role.getResourceIds().size(); i++) {
					roleResource = new RoleResource();
					roleResource.setRoleId(role.getId());
					roleResource.setResourceId(role.getResourceIds().get(i));
					roleResourceService.insert(roleResource);
				}
			}
		}
		return 1;
	}

	/**
	 * 
	 * @param 角色根据创建时间倒序
	 * @param gmc
	 * @param role
	 *            角色实体类
	 * @return
	 */
	public Page<Role> page(Role role) {
		role.setOrderBy("create_date desc");
		long count = mapper.count(role);
		Page<Role> page = new Page<Role>(role.getPageIndex_(),
				role.getPageSize_());
		List<Role> roleList = mapper.find(role);

		for (int i = 0; i < roleList.size(); i++) {

			// 得到角色的权限信息
			List<RoleResource> roleResourceList = roleResourceService
					.queryByRoleId(roleList.get(i).getId());
			// 存入权限
			List<Long> resourceList = new ArrayList<Long>();

			for (int j = 0; j < roleResourceList.size(); j++) {
				resourceList.add(roleResourceList.get(j).getResourceId());
			}

			roleList.get(i).setResourceIds(resourceList);
		}

		page.setData(roleList);
		page.setTotalCount(count);
		return page;

		//
		//
		//
		// role.setOrderBy("create_date desc");
		// int limitStart = role.getLimitStart(), limitEnd = role.getLimitEnd();
		// long count = mapper.count(role);
		// Page<Role> page = new Page<Role>(
		// (int) (limitEnd / (limitEnd - limitStart)),
		// (limitEnd - limitStart));
		// List<Role> roleList = mapper.find(role);
		// // 如果有roleId
		// if (role.getId() != null) {
		// // 得到角色的权限信息
		// List<RoleResource> roleResourceList = roleResourceService
		// .queryByRoleId(role.getId());
		// // 存入权限
		// List<Long> resourceList = new ArrayList<Long>();
		//
		// for (int i = 0; i < roleResourceList.size(); i++) {
		// resourceList.add(roleResourceList.get(i).getResourceId());
		// }
		//
		// roleList.get(0).setResourceIds(resourceList);
		// }
		//
		// page.setData(roleList);
		// page.setTotalCount(count);
		// return page;
	}

	/**
	 * @param 删除角色
	 * @param gmc
	 * @param roleId
	 *            角色id
	 * @return
	 */
	public int deleteByRoleId(Role role) {
		// 1、判断是否有用户采用该角色
		UserRole userRole = new UserRole();
		userRole.setRoleId(role.getId());
		if (userRoleMapper.find(userRole).size() > 0) {
			// 不可删除
			return 2;
		}
		// 2、查询是否角色和权限关联表有数据
		if (roleResourceMapper.queryByRoleId(role.getId()).size() > 0) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(role.getId());
			roleResourceMapper.deleteByRoleId(roleResource);
		}
		int remove = roleMapper.removeById(role.getId());
		if (remove > 0) {
			return 1;
		}
		return 0;
	}
}
